package controllers

import (
	"go_wep_demo/common"
	"go_wep_demo/dao/mysql"
	"go_wep_demo/logic"
	"go_wep_demo/models"
	"strconv"

	"github.com/gin-gonic/gin"
)

func SaveArticleHandler(c *gin.Context) {
	//接收参数
	var err error
	//1、参数校验
	var data = new(models.ParamSaveArticle)
	err = c.ShouldBind(data)
	if err != nil {
		ResponseErrorWithMsg(c, CodeInvalidParam, GetErrorMsg(err))
		return
	}
	//2、业务处理
	var id int64
	//检查文章分类是否存在
	typeExist := mysql.CheckTypeExist(data.TypeId)
	if !typeExist {
		ResponseErrorWithMsg(c, CodeInvalidParam, "文章分类不存在")
		return
	}
	id, err = logic.SaveArticle(data)
	if err != nil {
		ResponseError(c, CodeSystemBusy)
		return
	}
	m := map[string]interface{}{
		"article_id": id,
	}
	//3、返回响应
	ResponseSuccess(c, m)
}

func GetArticleHandler(c *gin.Context) {
	//接收参数
	idStr := c.Param("article_id")
	articleId, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		ResponseError(c, CodeInvalidParam)
		return
	}
	//2、获取文章
	var data models.ArticleInfo
	data, err = mysql.GetArticleInfo(articleId)
	if err != nil {
		ResponseErrorWithMsg(c, CodeInvalidParam, "文章不存在")
		return
	}
	data.TypeName = mysql.GetTypeNameById(data.TypeId)
	data.CreateTime = common.TrainTime(data.CreateTime)
	//3、返回响应
	ResponseSuccess(c, data)
}
